<template>
  <n-space class="go-mt-0" :wrap="false">
    <n-cascader
      v-model:value="previewSiteId"
      placeholder="没啥用的值"
      check-strategy="child"
      :options="options"
      :filterable="true"
      @update:value="handleSiteIdChange"
    />
    <n-button v-for="item in comBtnList" :key="item.title" :type="item.type" ghost @click="item.event">
      <template #icon>
        <component :is="item.icon"></component>
      </template>
      <span>{{ item.title }}</span>
    </n-button>
  </n-space>
  <n-modal v-model:show="showModal" preset="dialog" title="发布确认" positive-text="确认" negative-text="取消">
    <div>234</div>
  </n-modal>
  <!-- @positive-click="submitCallback"
    @negative-click="cancelCallback" -->
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { renderIcon, goDialog, fetchPathByName, routerTurnByPath, setSessionStorage, getLocalStorage } from '@/utils'
import { PreviewEnum } from '@/enums/pageEnum'
import { StorageEnum } from '@/enums/storageEnum'
import { useRoute } from 'vue-router'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { syncData } from '../../ContentEdit/components/EditTools/hooks/useSyncUpdate.hook'
import { icon } from '@/plugins'
import { cloneDeep } from 'lodash'
import { updateConfigApi, uploadPicture } from '@/api/cloud/config'
import { getDomainListApi, getSitesApi } from '@/api/cloud/domain'
import html2canvas from 'html2canvas'
import { PageType } from '@/views/project/items/index.d'
import { domainid } from '@/utils/cloud/utils'
import useStorage from '@/hooks/cloud/storage'

const { getStorage, setStorage } = useStorage()

const { BrowsersOutlineIcon, SaveIcon, SendIcon, AnalyticsIcon } = icon.ionicons5
const chartEditStore = useChartEditStore()

const routerParamsInfo = useRoute()

// 获取演示的租户和站点
const options = ref([])
const previewSiteId = ref('')
const getSiteOptions = async () => {
  const res: any = await getDomainListApi()
  if (res.msg) {
    Promise.all(
      res.msg.map(async (item: any) => {
        const siteRes: any = await getSitesApi({ domainid: item.id })
        return {
          value: item.id,
          label: `${item.name}(${item.path})`,
          children: siteRes.msg.map((val: any) => {
            return {
              value: val.id,
              label: val.item_label
            }
          })
        }
      })
    ).then((result: any) => {
      sessionStorage.setItem('domainStationList', JSON.stringify(result))
      options.value = result
      previewSiteId.value = getStorage('activeSiteId') || ''
    })
  }
}
const handleSiteIdChange = (value: string, current: any, parent: any) => {
  setStorage('activeSiteId', value)
  setStorage('previewDomainId', parent[0].value)
}

onMounted(() => {
  const domainStationList = sessionStorage.getItem('domainStationList')
  if (domainStationList) {
    options.value = JSON.parse(domainStationList)
    previewSiteId.value = getStorage('activeSiteId') || ''
  } else {
    getSiteOptions()
  }
})

// 预览
const previewHandle = () => {
  const path = fetchPathByName(PreviewEnum.CHART_PREVIEW_NAME, 'href')
  if (!path) return
  const { id } = routerParamsInfo.params
  // id 标识
  const previewId = typeof id === 'string' ? id : id[0]
  const storageInfo = chartEditStore.getStorageInfo()
  const sessionStorageInfo = getLocalStorage(StorageEnum.GO_CHART_STORAGE_LIST) || []

  if (sessionStorageInfo?.length) {
    const repeateIndex = sessionStorageInfo.findIndex((e: { id: string }) => e.id === previewId)
    // 重复替换
    if (repeateIndex !== -1) {
      sessionStorageInfo.splice(repeateIndex, 1, { id: previewId, ...storageInfo })
      setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, sessionStorageInfo)
    } else {
      sessionStorageInfo.push({
        id: previewId,
        ...storageInfo
      })
      setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, sessionStorageInfo)
    }
  } else {
    setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, [{ id: previewId, ...storageInfo }])
  }
  // 跳转
  routerTurnByPath(path, ['page', previewId], undefined, true)
}

// 保存 -> 保存到配置列表
const saveHandle = async (command = 'save') => {
  const storageInfo = chartEditStore.getStorageInfo()
  let { id } = routerParamsInfo.params
  id = typeof id === 'string' ? id : id[1]

  // 导出图片
  const range = document.querySelector('.go-edit-range') as HTMLElement

  html2canvas(range, {
    backgroundColor: null,
    allowTaint: true,
    useCORS: true
  }).then(async (canvas: HTMLCanvasElement) => {
    const dataURL = canvas.toDataURL('image/png')

    // 将 DataURL 转换成 Blob 对象

    // 定义 DataURL 转换 Blob 的辅助函数
    function dataURLToBlob(dataURL: any) {
      let BlobConstructor = window.Blob
      // 解析 dataURL
      let mimeString = dataURL.split(',')[0].match(/:(.*?);/)[1]
      let byteCharacters = atob(dataURL.split(',')[1])
      let byteArrays = []
      for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        let slice = byteCharacters.slice(offset, offset + 512)
        let byteNumbers = new Array(slice.length)
        for (let i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i)
        }
        let byteArray = new Uint8Array(byteNumbers)
        byteArrays.push(byteArray)
      }
      return new BlobConstructor(byteArrays, { type: mimeString })
    }
    const blob = dataURLToBlob(dataURL)

    const formdata = new FormData()
    formdata.append('file', blob, `page_designer/covers/${id}.png`)

    const uploadRes: any = await uploadPicture(formdata)
    const editProjectInfo: PageType = chartEditStore.getEditProjectInfo
    let params = {
      app_application: 'page_designer',
      app_datasource: editProjectInfo.datasource,
      app_name: id,
      domain_id: domainid(true),
      ...editProjectInfo.content,
      name: storageInfo.editCanvasConfig.projectName,
      config: storageInfo,
      coverImg: uploadRes.msg[0].url
    }

    const res: any = await updateConfigApi(params)
    if (res.code === 200) {
      window['$message'].success('保存成功！')
    } else {
      window['$message'].error('保存失败')
    }
  })
}

const showModal = ref(false)
// 发布 -> 发布到站点/设备
const sendHandle = () => {
  // goDialog({
  //   message: '想体验发布功能，请前往 master-fetch 分支查看: https://gitee.com/MTrun/go-view/tree/master-fetch',
  //   positiveText: '了然',
  //   closeNegativeText: true,
  //   onPositiveCallback: () => {}
  // })
  showModal.value = true
}

const btnList = [
  {
    select: true,
    title: '同步内容',
    type: 'primary',
    icon: renderIcon(AnalyticsIcon),
    event: syncData
  },
  {
    select: true,
    title: '预览',
    icon: renderIcon(BrowsersOutlineIcon),
    event: previewHandle
  },
  {
    select: true,
    title: '保存',
    icon: renderIcon(SaveIcon),
    event: saveHandle
  }
  // {
  //   select: true,
  //   title: '保存并发布',
  //   icon: renderIcon(SendIcon),
  //   event: sendHandle
  // }
]

const comBtnList = computed(() => {
  if (chartEditStore.getEditCanvas.isCodeEdit) {
    return btnList
  }
  const cloneList = cloneDeep(btnList)
  cloneList.shift()
  return cloneList
})
</script>

<style lang="scss" scoped>
.align-center {
  margin-top: -4px;
}
</style>
